<template>
  <div>
    <el-card class="box-card">
      <el-row :gutter="8"
              type="flex"
              align="middle">
        <el-col :span="1.5">
          部门名称
        </el-col>
        <el-col :span="3">
          <el-input v-model='getParams.deptName'
                    placeholder="请输入分类名字"></el-input>
        </el-col>
        <el-col :span="1.5">
          状态
        </el-col>
        <el-col :span="3">
          <el-select placeholder="请选择"
                     v-model="getParams.status">
            <el-option label="正常"
                       :value="0">
            </el-option>
            <el-option label="停用"
                       :value="1">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary"
                     icon="el-icon-search"
                     @click="getTableList()">搜索</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button @click="refreshTable"
                     icon='el-icon-refresh'>重置</el-button>
        </el-col>
      </el-row>
      <div class="btnList">
        <el-row :gutter="8"
                type="flex"
                align="middle"
                class="btn_nav">
          <el-col :span="1.5">
            <el-button size="mini"
                       type="primary"
                       icon="el-icon-plus"
                       plain
                       @click="addXqq">新增</el-button>
          </el-col>

        </el-row>

        <el-row :gutter="8"
                type="flex"
                align="middle"
                class="btn_nav">

          <el-col :span="1.5">
            <el-button size="mini"
                       icon="el-icon-search"
                       circle></el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button @click="refreshTable"
                       size="mini"
                       icon="el-icon-refresh"
                       circle></el-button>
          </el-col>
        </el-row>
      </div>

      <!--  -->
      <el-table :data="menuList"
                v-loading="loading"
                style="width: 100%"
                :header-cell-style="{background:'#f8f8f9'}"
                row-key="deptId"
                :default-expand-all="false"
                :tree-props="{children:'children', hasChildren:'hasChildren'}">

        <el-table-column prop="deptName"
                         label="部门名称"
                         width="180">
        </el-table-column>

        <el-table-column prop="orderNum"
                         label="排序">
        </el-table-column>

        <el-table-column prop="status"
                         label="状态">
          <template slot-scope="scope">
            <span>{{scope.row.status==0?'正常':'停用'}}</span>
          </template>

        </el-table-column>
        <el-table-column prop="createTime"
                         label="创建时间">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="data">
            <el-button icon="el-icon-edit"
                       type="text"
                       @click="updateHandler(data.row.deptId)">修改</el-button>
            <el-button icon="el-icon-plus"
                       type="text"
                       @click="add(data.row)">新增</el-button>
            <el-button v-if="data.row.deptId!=100"
                       icon="el-icon-delete"
                       type="text"
                       @click="deleteHandler(data.row.deptId)">删除</el-button>
          </template>

        </el-table-column>
      </el-table>

    </el-card>

    <div>
      <el-dialog :title="tip?'添加部门':'修改部门'"
                 @closed="closed"
                 :visible.sync="dialogVisible"
                 width="40%">
        <el-form :model="formData"
                 ref="ruleForm"
                 label-width="80px">
          <el-form-item v-if="isParent"
                        label="上级部门"
                        prop="name">
            <el-select v-model="form.deptId"
                       :filter-method="remoteMethod"
                       filterable
                       size="small"
                       style="width:100%"
                       placeholder="请选择"
                       ref="selectTree">
              <el-option :label="form.deptName"
                         :value="form.deptId"
                         hidden>
              </el-option>
              <el-tree :data="treeList"
                       :props="defaultProps"
                       node-key="deptId"
                       accordion
                       ref="tree"
                       :filter-node-method="filterNode"
                       highlight-current
                       @node-click="handleNodeClick" />
              <!-- <el-option :label="form.value"
                         style="height: auto"
                         :value="form.menuId">
                <el-tree ref="tree"
                         :data="treeList"
                         :props="defaultProps"
                         node-key="menuId"
                         accordion
                         :filter-node-method="filterNode"
                         highlight-current
                         @node-click="handleNodeClick" />
              </el-option> -->
            </el-select>
          </el-form-item>

          <!--  -->
          <el-row style="display:flex">
            <el-col>
              <el-form-item label="部门名称"
                            prop="postCode">
                <el-input v-model="formData.deptName"
                          size="small"
                          placeholder="请输入部门名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item prop="postSort"
                            label="显示顺序">
                <el-input-number size="small"
                                 v-model="formData.orderNum"
                                 controls-position="right"
                                 :min="0"
                                 :max="10000000"></el-input-number>
              </el-form-item>
            </el-col>

          </el-row>
          <!--  -->
          <el-row style="display:flex">
            <el-col>
              <el-form-item label="负责人"
                            prop="postCode">
                <el-input v-model="formData.leader"
                          size="small"
                          placeholder="请输入负责人"></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item prop="postSort"
                            label="联系电话">
                <el-input size="small"
                          v-model="formData.phone"
                          placeholder="联系电话"></el-input>
              </el-form-item>
            </el-col>

          </el-row>

          <!--  -->
          <el-row style="display:flex">
            <el-col>
              <el-form-item label="邮箱"
                            prop="postCode">
                <el-input v-model="formData.email"
                          size="small"
                          placeholder="请输入邮箱"></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item prop="postSort"
                            label="部门状态">
                <template>
                  <el-radio v-model="formData.status"
                            label="0">正常</el-radio>
                  <el-radio v-model="formData.status"
                            label="1">停用</el-radio>
                </template>
              </el-form-item>
            </el-col>

          </el-row>

        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addXqqType">确 定</el-button>
        </span>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import quillEditor from '../../../components/Quill'
// import { quillEditor } from 'vue-quill-editor'
export default {
  components: { quillEditor },
  data() {
    return {
      isParent: true,
      formData: {
        ancestors: null,
        children: [],
        createBy: null,
        createTime: null,
        delFlag: null,
        deptId: null,
        deptName: null,
        email: null,
        leader: null,
        orderNum: null,
        params: {},
        parentId: null,
        parentName: null,
        phone: null,
        remark: null,
        searchValue: null,
        status: '0',
        updateBy: null,
        updateTime: null
      },
      getParams: {
        deptName: '',
        status: ''
      },
      arr: [],
      tableData: [],
      menuList: [],
      treeList: [],
      tip: true,
      // 选中的
      loading: true,
      dialogVisible: false,
      form: {
        deptId: '',
        deptName: ''
      },
      defaultProps: {
        children: 'children',
        label: 'deptName'
      }
    }
  },
  mounted() {
    this.loading = true
    this.getTableList()
  },
  methods: {
    updatadata() {
      this.tip = false
      this.updateHandler(this.checkItem[0].id)
    },
    delMore() {
      let ids = this.checkItem.map((el) => el.id)
      this.deleteHandler(ids)
    },
    deleteHandler(id) {
      this.$confirm(`是否确认删除编号为${id.toString()}的数据项?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let data = await this.$axios.delete(`system/dept/${id.toString()}`)
          console.log(data)
          if (data.data.code != 200) this.$message.error(data.data.msg)
          this.$message({
            type: 'success',
            message: data.data.msg
          })
          this.getTableList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },

    //
    async updateHandler(id) {
      this.tip = false
      let { data } = await this.$axios.get(`system/dept/${id}`)
      let { data: res } = await this.$axios.get('system/dept/list')
      // this.treeList =
      this.treeList = this.getChildren(res.data, 0)
      this.arr = res.data
      if (data.data.parentId != 0) {
        this.isParent = true
        let obj = this.arr.filter((el) => el.deptId == data.data.parentId)
        this.form.deptId = obj[0].deptId
        this.form.deptName = obj[0].deptName
      } else {
        this.isParent = false
        this.form.deptId = data.data.deptId
        this.form.deptName = data.data.deptName
      }

      this.formData = data.data
      this.dialogVisible = true
    },
    // close
    closed() {
      this.formData = {
        ancestors: null,
        children: [],
        createBy: null,
        createTime: null,
        delFlag: null,
        deptId: null,
        deptName: null,
        email: null,
        leader: null,
        orderNum: null,
        params: {},
        parentId: null,
        parentName: null,
        phone: null,
        remark: null,
        searchValue: null,
        status: '0',
        updateBy: null,
        updateTime: null
      }
    },

    async addXqqType() {
      let data = null
      this.formData.parentId = this.form.deptId
      if (!this.formData.deptId) {
        data = await this.$axios.post('system/dept', this.formData)
      } else {
        data = await this.$axios.put('system/dept', this.formData)
      }
      if (data.data.code != 200) return this.$message.error(data.data.msg)
      this.$message({
        message: data.data.msg,
        type: 'success'
      })
      this.dialogVisible = false
      this.getTableList()
      this.closed()
    },

    async add(data) {
      this.isParent = true
      this.tip = false
      // let { data: res } = await this.$axios.get('system/dept/list')
      // // this.treeList =
      // this.treeList = this.getChildren(res.data, 0)
      this.form.deptId = data.deptId
      this.form.deptName = data.deptName
      this.dialogVisible = true
    },
    async addXqq() {
      this.isParent = true
      this.tip = true
      this.form = {
        deptId: '',
        deptName: ''
      }
      this.dialogVisible = true
      let { data } = await this.$axios.get('system/dept/list')
      // this.treeList =
      this.treeList = this.getChildren(data.data, 0)
      // this.form.deptId = 0
      // this.form.value = '主菜单'
    },
    getChildren(list, rootValue) {
      let arr = []

      list.forEach((item) => {
        if (item.parentId === rootValue) {
          const children = this.getChildren(list, item.deptId) // 找到之后 就要去找 item 下面有没有子节点
          if (children.length) {
            item.children = children // 如果children的长度大于0 说明找到了子节点
          }
          arr.push(item) // 将内容加入到数组中
        }
      })
      return arr // 返回新数组
    },

    //
    handleNodeClick(data) {
      this.form = {
        deptId: data.deptId,
        deptName: data.deptName
      }
      // 使 input 失去焦点，并隐藏下拉框
      this.$refs.selectTree.blur()
    },
    remoteMethod(val) {
      this.$refs.tree.filter(val)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.deptName.indexOf(value) !== -1
    },

    // 刷新
    refreshTable() {
      this.getParams = { deptName: '', status: '' }
      this.getTableList()
    },
    async getTableList() {
      this.loading = true
      this.menuList = []
      let { data } = await this.$axios.get('system/dept/list', { params: this.getParams })
      this.tableData = data.data
      this.menuList = this.getChildren(data.data, 0)
      this.arr = data.data
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}

.el-card__body {
  padding: 10px;
  padding-top: 20px;
  .btnList {
    margin-bottom: 8px;
    margin-top: 15px;
    display: flex;
    justify-content: space-between;
  }
  .page {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>